package com.googlecode.napp.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;

public class Listener{
//public class ListenIncomingTcpConnection {
    public Listener() {
    	StringBuffer buffer = new StringBuffer();
        long start = System.currentTimeMillis();
    	System.out.println("Listener init.");
        ServerSocket serverSocket = null;
        Socket client = null;
        PrintWriter out = null;
        
        serverSocket = makeServer(serverSocket);
        InputStreamReader in = null;       
        
        while (true) {

            try {
            	client = serverSocket.accept();
            	out = new PrintWriter(client.getOutputStream(), true);
                in = new InputStreamReader(client.getInputStream());
                Output("Connection made with:" + client.getInetAddress() + ":" + client.getPort());
                out.print("TEST TEST TEST TEST TEST TEST TEST");
            } catch (IOException e1) {
                System.out.println(e1);
                e1.printStackTrace();
            }
            try {    
            	int ch;
            	Reader input = new BufferedReader(in);
            	while((ch = input.read()) != -1 )
            	{
            		buffer.append((char)ch);
            	}
            	serverIn.serverIn(buffer.toString());
            	String[] split = buffer.toString().split("/n");
            	user user = new user(split[0], client.getInetAddress().toString(), client.getPort());
            	buffer.delete(0, buffer.length());
                
            } catch(Exception e) {
                System.out.println(e);		
                if(buffer != null) buffer.delete(0, buffer.length());
            } finally {
                try{
                    client.close();
                }catch(Exception e){
                    System.out.println(e);
                    
                }
            }
        }//while 
    }//PSVM

    public static void Output(String out)
    {
    	System.out.println(System.currentTimeMillis() + " : " + out);
    }
	private ServerSocket makeServer(ServerSocket serverSocket) {
		// TODO Auto-generated method stub
		 try {
	        	System.out.println("Creating the server object...");
	            serverSocket = new ServerSocket(4447);
	            System.out.println("Waiting for the connection...");
	        } catch (IOException e1) {
	            System.out.println(e1);
	        }
	        return serverSocket;
	}

}
